import { EventSubscriber, EntitySubscriberInterface, InsertEvent, UpdateEvent } from 'typeorm';
import { RequestContext } from '../../../../context/request.context';
import { AreaEntity } from '../../../area/entities/area.entity';

/**
 * 区域订阅器
 */
@EventSubscriber()
export class AreaSubscriber implements EntitySubscriberInterface<AreaEntity> {
  /**
   * Returns the class of the entity to which events will listen.
   * If this method is omitted, then subscriber will listen to events of all entities.
   */
  listenTo() {
    return AreaEntity;
  }

  /**
   * Called before entity is inserted to the database.
   * @param event insert event
   */
  beforeInsert(event: InsertEvent<AreaEntity>) {
    const currentUser = RequestContext.currentUser();
    if (!currentUser) return;
    if (!event.entity) return;

    if ('jobId' in currentUser && currentUser.jobId) event.entity.creatorJobId = currentUser.jobId;
    if ('uuid' in currentUser && currentUser.uuid) event.entity.createdBy = currentUser.uuid;
  }

  /**
   * Called before entity is updated to the database.
   * @param event update event
   */
  beforeUpdate(event: UpdateEvent<AreaEntity>) {
    const currentUser = RequestContext.currentUser();
    if (!currentUser) return;
    if (!event.entity) return;

    if ('uuid' in currentUser && currentUser.uuid) event.entity.updatedBy = currentUser.uuid;
  }
}
